<template>
  <div class="contract-add">
    <!-- 顶部导航区域 -->
    <div class="header-wrapper">
      <!-- 顶部导航 -->
      <div class="header">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <div class="header-title">合同审批</div>
      </div>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
      <!-- 合同基本信息 -->
      <div class="form-field">
        <div class="field-label">合同名称</div>
        <van-field
          v-model="formData.name"
          placeholder="请输入合同名称"
          :border="false"
          class="custom-field"
          autocomplete="off"
        />
      </div>

      <!-- 文件上传组件（使用 Vant Uploader 封装） -->
      <div class="form-field form-contract-uploader" @click="openContractUploaderInput($event)">
        <div class="field-label">合同附件</div>
        <VantUploader ref="contractUploaderCompRef" v-model="fileList" :max-file-count="5" :max-file-size-m-b="10" @deleted="onFileDeleted" />
      </div>

      <div class="form-field">
        <div class="field-label">金额类型</div>
        <van-field
          v-model="formData.amountTypeText"
          is-link
          readonly
          placeholder="请选择金额类型"
          @click="showAmountTypeSelector"
          :border="false"
          class="custom-field"
          autocomplete="off"
        />
      </div>

      <!-- 合同总金额 - 仅在选择收入或支出时显示 -->
      <div
        v-if="
          formData.amountTypeText === '收入' ||
          formData.amountTypeText === '支出'
        "
        class="form-field"
      >
        <div class="field-label">合同总金额（元）</div>
        <van-field
          v-model="formData.totalAmount"
          placeholder="请输入"
          type="number"
          :border="false"
          class="custom-field"
          autocomplete="off"
        />
      </div>

      <!-- 合同类型选择 -->
      <div class="form-field">
        <div class="field-label">合同类型</div>
        <van-field
          v-model="formData.contractTypeText"
          is-link
          readonly
          placeholder="请选择合同类型"
          @click="showContractTypePopup = true"
          :border="false"
          class="custom-field"
          autocomplete="off"
        />
      </div>

      <div class="form-field textarea-field">
        <div class="field-label">合同说明</div>
        <van-field
          v-model="formData.contractNote"
          placeholder="请输入合同描述"
          type="textarea"
          rows="3"
          :border="false"
          class="custom-field"
          maxlength="2000"
          show-word-limit
          @input="onDescriptionInput"
          autocomplete="off"
        />
      </div>

      <!-- 委托信息 -->
      <div class="form-section-title">委托方信息</div>
      <div class="form-field our-party-first">
        <div class="field-label">委托人名称</div>
        <van-field
          v-model="formData.clientName"
          placeholder="请输入委托人名称"
          :border="false"
          class="custom-field"
          autocomplete="off"
        />
      </div>
      <div class="form-field our-party-second">
        <div class="field-label">委托人类型</div>
        <van-field
          v-model="formData.clientTypeText"
          is-link
          readonly
          :border="false"
          class="custom-field"
          placeholder="请选择委托人类型"
          @click="showPrincipalTypeSelector"
          autocomplete="off"
        />

        <van-action-sheet
          title="委托人类型"
          v-model:show="showPrincipalTypePicker"
          :actions="principalTypeActions"
          @select="onPrincipalTypeSelect"
          cancel-text="取消"
          close-on-click-action
        />
      </div>

      <!-- 对方信息 -->
      <div class="form-section-title">对方信息</div>
      <div class="form-field counterparty-first">
        <div class="field-label">对方名称</div>
        <van-field
          v-model="formData.otherEntityName"
          placeholder="请输入对方名称"
          :border="false"
          class="custom-field"
          autocomplete="off"
        />
      </div>

      <div class="form-field counterparty-second">
        <div class="field-label">对方负责人</div>
        <van-field
          v-model="formData.otherCharge"
          placeholder="请输入方负责人"
          :border="false"
          class="custom-field"
          autocomplete="off"
        />
      </div>

      <div class="form-field">
        <div class="field-label">签署方式</div>
        <van-field
          v-model="formData.signingMethodText"
          is-link
          readonly
          placeholder="请选择签署方式"
          @click="showSignMethodPicker = true"
          :border="false"
          class="custom-field"
          autocomplete="off"
        />
      </div>

      <div class="form-field textarea-field">
        <div class="field-label">签署日期</div>
        <van-field
          v-model="formData.signTime"
          is-link
          readonly
          name="signDate"
          class="custom-field"
          placeholder="点击选择时间"
          @click="showSignDateSelector"
          autocomplete="off"
        />
      </div>

      <div class="form-field">
        <div class="field-label">印章类型</div>
        <van-field
          v-model="formData.sealTypeText"
          is-link
          readonly
          placeholder="请选择印章类型"
          @click="showSealTypeSheet = true"
          :border="false"
          autocomplete="off"
          class="custom-field"
        />
      </div>

      <!-- 流程步骤 -->
      <div class="form-container">
        <div class="process-step-container">
          <div class="process-step-title">流程</div>
          <div class="process-steps">
            <div
              v-for="(step, index) in approvalSteps"
              :key="index"
              class="process-step"
              :class="{ 'is-last': index === approvalSteps.length - 1 }"
            >
              <!-- 左侧步骤条 -->
              <div class="step-line-container">
                <div class="step-dot"></div>
                <div
                  v-if="index < approvalSteps.length - 1"
                  class="step-line"
                ></div>
              </div>

              <!-- 右侧人员信息 -->
              <div class="step-info">
                <div class="step-title-container">
                  <div class="step-title">{{ step.title }}</div>
                  <div v-if="step.subtitle" class="step-subtitle">
                    {{ step.subtitle }}
                  </div>
                </div>
                <div class="step-person">
                  <div class="person-avatar">
                    <!-- 使用统一的头像组件 -->
                    <AvatarDisplay :url="step.url" :name="step.name" />
                  </div>
                  <div class="person-name">{{ step.name }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作按钮 -->
      <div class="action-buttons">
        <van-button class="action-btn submit-btn" @click="submitContract">
          提交
        </van-button>
      </div>
    </div>
  </div>

  <!-- 合同类型级联选择器 -->
  <van-popup v-model:show="showContractTypePopup" round position="bottom">
    <van-cascader
      v-model="selectedContractType"
      title="请选择合同类型"
      :options="contractTypeOptions"
      @close="showContractTypePopup = false"
      @finish="onContractTypeFinish"
    />
  </van-popup>

  <!-- 签署方式选择 -->
  <van-action-sheet
    v-model:show="showSignMethodPicker"
    :actions="signMethodActions"
    title="选择签署方式"
    @select="onSignMethodSelect"
    cancel-text="取消"
  />

  <!-- 印章类型选择器 -->
  <van-action-sheet
    v-model:show="showSealTypeSheet"
    title="选择印章类型（可多选）"
    :close-on-click-action="false"
    cancel-text="确定"
    @cancel="confirmSealTypeSelection"
  >
    <div class="seal-type-list">
      <div
        v-for="item in sealTypeActions"
        :key="item.value"
        class="seal-type-item"
        @click="toggleSealType(item)"
      >
        <span>{{ item.name }}</span>
        <van-checkbox :model-value="item.checked" />
      </div>
    </div>
  </van-action-sheet>

  <!-- 金额类型选择 -->
  <van-action-sheet
    v-model:show="showAmountTypePicker"
    :actions="amountTypeActions"
    title="选择金额类型"
    @select="onAmountTypeSelect"
    cancel-text="取消"
  />

  <!-- 签署日期选择器 -->
  <van-popup v-model:show="showDatePicker" position="bottom">
    <van-date-picker
      v-model="signDateArray"
      title="选择日期"
      @confirm="onDateConfirm"
      @cancel="showDatePicker = false"
    />
  </van-popup>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { useRouter, onBeforeRouteLeave } from "vue-router";
import { showToast } from "vant";
import { addContract, queryFlow, getUserPicture } from "@/api/contract";
import { smartGoBack } from "@/utils/navigation";
import {
  amountTypeOptions,
  signMethodOptions,
  sealTypeOptions,
} from "@/utils/enums";
import AvatarDisplay from "@/components/UserAvatar/AvatarDisplay.vue";
import { navigateAfterSubmit } from "@/utils/navigation";
import VantUploader from "@/components/UploadFiled/VantUploader.vue";
import { openUploadFromRowClick } from "@/utils/uploadTrigger";
import { useHardwareBackCleanup } from "@/utils/hardwareBackCleanup";
defineOptions({ name: 'ContractAdd' })

const router = useRouter();

// 让整行（含标签）都能触发上传：点击时主动触发内部 input[type=file]
const contractUploaderCompRef = ref(null);
const openContractUploaderInput = (e) => {
  openUploadFromRowClick(e, contractUploaderCompRef.value);
};

// 重置新增合同页状态
const resetContractAddState = () => {
  // 清空表单数据
  formData.name = "";
  formData.amountType = "";
  formData.amountTypeText = "";
  formData.bigType = "";
  formData.smallType = "";
  formData.contractNote = "";
  formData.totalAmount = "";
  formData.clientName = "";
  formData.clientType = "";
  formData.clientTypeText = "";
  formData.otherEntityName = "";
  formData.otherCharge = "";
  formData.signingMethod = "";
  formData.signingMethodText = "";
  formData.signTime = "";
  formData.sealType = [];
  formData.sealTypeText = "";
  formData.description = "";
  formData.contractTypeText = "";
  
  // 清空附件
  fileList.value = [];
  uploadedFiles.value = "";
  
  // 关闭选择器开关
  showContractTypePopup.value = false;
  showSignMethodPicker.value = false;
  showSealTypeSheet.value = false;
  showDatePicker.value = false;
  showAmountTypePicker.value = false;
  showPrincipalTypePicker.value = false;
  
  // 重置印章类型选择器状态
  sealTypeActions.value.forEach(item => {
    item.checked = false;
  });
  
  // 重置审批步骤
  approvalSteps.value = [];
  submitting.value = false;
  
  // 重置日期选择器数组
  signDateArray.value = getCurrentDateArray();
};

// 绑定手机系统返回（popstate）时的清理逻辑
useHardwareBackCleanup('ContractAdd', resetContractAddState);

// 返回上一页
const goBack = () => {
  // 先重置本地状态
  resetContractAddState();
  // 再清除本页的 KeepAlive 缓存
  window.dispatchEvent(new CustomEvent('clear-keepalive-cache', { detail: { name: 'ContractAdd' } }));
  // 统一返回逻辑
  smartGoBack(router);
};

// 提交状态
const submitting = ref(false);

// 表单数据
const formData = reactive({
  // 基本信息
  name: "", // 合同名称
  amountType: "", // 金额类型
  amountTypeText: "", // 金额类型显示文本
  bigType: "", // 合同一级类型（业务类/行政事务类）
  smallType: "", // 合同二级类型（根据一级类型的子项）
  contractNote: "", // 合同说明
  totalAmount: "", // 合同总金额

  // 委托信息
  clientName: "", // 委托人名称
  clientType: "", // 委托人类型
  clientTypeText: "", // 委托人类型显示文本

  // 对方信息
  otherEntityName: "", // 对方主体名称
  otherCharge: "", // 对方负责人

  // 签署信息
  signingMethod: "", // 签署方式
  signingMethodText: "", // 签署方式显示文本
  signTime: "", // 签署时间

  // 印章信息
  sealType: [], // 印章类型（支持多选）
  sealTypeText: "", // 印章类型显示文本

  // 其他
  description: "", // 描述
  contractTypeText: "", // 合同类型显示文本
});

// 流程步骤数据
const currentStep = ref(0);
const approvalSteps = ref([]);

// 获取当前日期数组格式
const getCurrentDateArray = () => {
  const now = new Date();
  const year = now.getFullYear().toString();
  const month = (now.getMonth() + 1).toString().padStart(2, "0");
  const day = now.getDate().toString().padStart(2, "0");
  return [year, month, day];
};

// 日期选择器数组变量
const signDateArray = ref(getCurrentDateArray());

// 获取姓名后两位字符作为头像
const getNameInitials = (name) => {
  if (!name) return "";
  return name.length >= 2 ? name.slice(-2) : name;
};

// 加载用户头像
const loadUserAvatar = async (url) => {
  if (!url) return "text"; // 返回标识符表示使用文字头像

  try {
    const blob = await getUserPicture(url);
    return URL.createObjectURL(blob);
  } catch (error) {
    console.error("加载头像失败:", error);
    return "text"; // 加载失败时使用文字头像
  }
};

// 查询流程信息
const loadFlowData = async () => {
  try {
    const response = await queryFlow();

    if (response.code === 0 && response.data) {
      const { firstApprover, secondApprover, thirdApprover } = response.data;

      // 收集所有有效的审批人
      const approvers = [];

      if (firstApprover && Object.keys(firstApprover).length > 0) {
        approvers.push(firstApprover);
      }

      if (secondApprover && Object.keys(secondApprover).length > 0) {
        approvers.push(secondApprover);
      }

      if (thirdApprover && Object.keys(thirdApprover).length > 0) {
        approvers.push(thirdApprover);
      }

      // 检查是否有审批人
      if (approvers.length === 0 || approvers.length === 1) {
        // Toast提示并禁用提交按钮
        showToast("该公司尚未设置CEO或组织架构尚未完善");
        submitting.value = true; // 禁用提交按钮
        return;
      }

      // 动态构建审批步骤数组，级别从1开始
      const steps = [];

      for (let i = 0; i < approvers.length; i++) {
        const approver = approvers[i];
        const avatar = await loadUserAvatar(approver.url);
        steps.push({
          title: "审批人",
          subtitle: `${i + 1}级审批`,
          name: approver.name,
          avatar: avatar,
          url: approver.url,
          id: approver.id,
        });
      }

      // 更新审批步骤
      approvalSteps.value = steps;
    }
  } catch (error) {
    console.error("查询流程失败:", error);
    showToast("加载流程信息失败");
  }
};

// 选择器显示状态
const showContractTypePopup = ref(false);
const showSignMethodPicker = ref(false);
const showSealTypeSheet = ref(false);
const showDatePicker = ref(false);
const showAmountTypePicker = ref(false);

// 合同类型选项数据结构
const contractTypeOptions = [
  {
    text: "业务类",
    value: "1",
    children: [
      { text: "民事", value: "1" },
      { text: "刑事", value: "2" },
      { text: "其他", value: "3" },
    ],
  },
  {
    text: "行政事务类",
    value: "2",
    children: [
      { text: "劳动劳务合同", value: "1" },
      { text: "采购合同", value: "2" },
      { text: "其他", value: "3" },
    ],
  },
];

// 处理合同类型选择完成
const onContractTypeFinish = ({ selectedOptions }) => {
  const mainType = selectedOptions[0];
  const subType = selectedOptions[1];

  // 赋值给后端需要的字段
  formData.bigType = mainType.value; // 1-业务类 2-行政事务类
  formData.smallType = subType.value; // 1/2/3 不同含义取决于 bigType
  // 显示给用户的文案
  formData.contractTypeText = `${mainType.text}/${subType.text}`; // 使用完整路径显示

  showContractTypePopup.value = false;
};

// 显示印章类型选择器
const showSealTypeSelector = () => {
  showSealTypeSheet.value = true;
};

// 金额类型选择器动作
const amountTypeActions = amountTypeOptions.map((item) => ({
  name: item.name,
  value: item.value,
}));

// 签署方式选择器动作
const signMethodActions = signMethodOptions.map((item) => ({
  name: item.name,
  value: item.value,
}));

// 印章类型选择器动作
const sealTypeActions = ref(
  sealTypeOptions.map((item) => ({
    name: item.name,
    value: item.value,
    checked: false, // 添加选中状态
  }))
);

// 印章类型选择处理
const toggleSealType = (item) => {
  item.checked = !item.checked;
  const selectedTypes = sealTypeActions.value.filter((type) => type.checked);
  formData.sealType = selectedTypes.map((type) => type.value);
  formData.sealTypeText = selectedTypes.map((type) => type.name).join("、");
};

// 确认印章类型选择
const confirmSealTypeSelection = () => {
  showSealTypeSheet.value = false;
};

// 金额类型选择处理
const onAmountTypeSelect = (action) => {
  formData.amountType = action.value;
  formData.amountTypeText = action.name;
  showAmountTypePicker.value = false;
};

// 签署方式选择处理
const onSignMethodSelect = (action) => {
  formData.signingMethod = action.value;
  formData.signingMethodText = action.name;
  showSignMethodPicker.value = false;
};

// 显示金额类型选择器
const showAmountTypeSelector = () => {
  showAmountTypePicker.value = true;
};

// 显示签订时间选择器
const showSignDateSelector = () => {
  showDatePicker.value = true;
};

// 签署日期确认
const onDateConfirm = ({ selectedValues }) => {
  formData.signTime = selectedValues.join("/");
  showDatePicker.value = false;
};

// 合同说明输入处理
const onDescriptionInput = (value) => {
  // 限制字符数不超过2000
  if (value.length > 2000) {
    formData.description = value.substring(0, 2000);
    showToast("合同说明不能超过2000字符");
  }
};

// 使用 Vant Uploader 的文件列表
const fileList = ref([]);

// 删除事件
const onFileDeleted = (file) => {
  // 父层兜底删除：若子组件未同步到 v-model，这里按引用/路径/文件名进行删除
  const sameFile = (a, b) => {
    if (!a || !b) return false;
    return (
      a === b ||
      (a.serverPath && b.serverPath && a.serverPath === b.serverPath) ||
      (a.uploadedPath && b.uploadedPath && a.uploadedPath === b.uploadedPath) ||
      (a.path && b.path && a.path === b.path) ||
      (a.file?.name && b.file?.name && a.file.name === b.file.name && a.file?.size === b.file?.size)
    );
  };
  const list = Array.isArray(fileList.value) ? fileList.value : [];
  const next = list.filter((x) => !sameFile(x, file));
  // 仅在确实发生变化时才赋值，避免无谓刷新
  if (next.length !== list.length) {
    fileList.value = next;
  }
  showToast('已删除附件');
};

// 统一的附件字符串（以逗号拼接的服务器路径）
const uploadedFiles = ref("");
// 同步 fileList 到附件字符串
watch(
  fileList,
  (list) => {
    const paths = (list || [])
      .map((f) => f.serverPath)
      .filter(Boolean)
      .join(",");
    uploadedFiles.value = paths;
    console.log("附件路径已更新:", uploadedFiles.value);
  },
  { deep: true }
);

// 表单提交
const submitContract = async () => {
  // 验证必填字段
  if (!formData.name) {
    showToast("请输入合同名称");
    return;
  }
  if (!formData.amountType) {
    showToast("请选择金额类型");
    return;
  }
  if (!formData.bigType || !formData.smallType) {
    showToast("请选择合同类型");
    return;
  }
  if (!formData.clientName) {
    showToast("请输入委托人名称");
    return;
  }
  if (!formData.clientType) {
    showToast("请输入委托人类型");
    return;
  }
  if (!formData.otherEntityName) {
    showToast("请输入对方主体名称");
    return;
  }
  if (!formData.otherCharge) {
    showToast("请输入对方负责人");
    return;
  }
  if (!formData.signingMethod) {
    showToast("请选择签署方式");
    return;
  }
  if (!formData.signTime) {
    showToast("请选择签署日期");
    return;
  }
  if (!formData.sealType) {
    showToast("请选择印章类型");
    return;
  }

  try {
    submitting.value = true;

    // 构建API参数
    const params = {
      name: formData.name,
      amountType: formData.amountType,
      // 按后端要求传递：bigType + smallType
      bigType: Number(formData.bigType),
      smallType: Number(formData.smallType),
      contractNote: formData.contractNote || "",
      clientName: formData.clientName,
      clientType: formData.clientType,
      otherEntityName: formData.otherEntityName,
      otherCharge: formData.otherCharge,
      signingMethod: formData.signingMethod,
      signTime: formData.signTime,
      sealType: formData.sealType,
      attachmentUrl: uploadedFiles.value, // 直接使用文件路径字符串（逗号分隔）
    };

    // 调用API
    const response = await addContract(params);

    if (response.code === 0) {
      showToast({ type: 'success', message: response.msg || "申请合同流程成功" });
      
      // 提交成功后先重置本地状态
      resetContractAddState();
      
      // 再清理本页缓存
      window.dispatchEvent(new CustomEvent('clear-keepalive-cache', { detail: { name: 'ContractAdd' } }));
      
      navigateAfterSubmit(router, response, "/contract");
    } else {
      showToast(response.msg || "提交失败，请重试");
    }
  } catch (error) {
    console.error("提交合同失败:", error);
    showToast("网络错误，请重试");
  } finally {
    submitting.value = false;
  }
};

// 组件挂载时加载流程数据
onMounted(() => {
  loadFlowData();
});

// 页面离开时的统一清理：
// - 前往附件预览（/file-preview*）或组织架构（/organization*）时保留数据；
// - 其它任何离开（包括系统返回/左滑、跳转详情等）一律清理，确保各端一致。
onBeforeRouteLeave((to) => {
  try {
    const destPath = to?.path || '';
    const goingToPreview = destPath.startsWith('/file-preview');
    const goingToOrganization = destPath.startsWith('/organization');

    // 预览或组织架构选择流程返回需要保留新增页数据
    if (goingToPreview || goingToOrganization) {
      return; // 不清理，保持表单与附件
    }

    // 其它场景（系统返回、左滑返回、提交成功后的跳转等）统一清理
    resetContractAddState();
    window.dispatchEvent(new CustomEvent('clear-keepalive-cache', { detail: { name: 'ContractAdd' } }));
  } catch (err) {
    console.warn('[ContractAdd] onBeforeRouteLeave cleanup failed:', err);
  }
});

// 委托人类型选项
const principalTypeOptions = [
  { name: "自然人", value: "1" },
  { name: "法人", value: "2" },
];

// 委托人类型选择器动作
const principalTypeActions = principalTypeOptions.map((item) => ({
  name: item.name,
  value: item.value,
}));

// 显示委托人类型选择器
const showPrincipalTypeSelector = () => {
  showPrincipalTypePicker.value = true;
};

// 委托人类型选择处理
const onPrincipalTypeSelect = (action) => {
  formData.clientType = action.value;
  formData.clientTypeText = action.name;
  showPrincipalTypePicker.value = false;
};

// 选择器显示状态
const showPrincipalTypePicker = ref(false);
</script>

<style lang="scss" scoped>
@import url("./style/add.scss");

.seal-type-list {
  max-height: 400px;
  overflow-y: auto;
  padding: 16px;
}

.seal-type-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  margin-bottom: 8px;
  background: #fff;
  border-radius: 4px;

  &:active {
    background: #f2f3f5;
  }

  span {
    font-size: 28px;
    color: #323233;
  }
}
</style>